import { defineStore } from "pinia";

export const useTodosStore = defineStore('todos', {
    state: () => ({
        list: JSON.parse(localStorage.getItem('todos')) || [
            { id: 1, name: '小程序', done: true },
            { id: 2, name: 'uniapp', done: true },
            { id: 3, name: 'vue3', done: false },
        ],
        filterArr: ['All', 'Active', 'Completed'],
        active: 'All'
    }),
    getters: {
        showList() {
            if (this.active === 'All') {
                return this.list
            } else if (this.active === 'Active') {
                return this.list.filter(v => !v.done)
            } else if (this.active === 'Completed') {
                return this.list.filter(v => v.done)
            }
        }
    },
    actions: {
        changeActive(item) {
            this.active = item
        },
        changeDone(id) {
            // console.log('id -----> ', id);
            const obj = this.list.find(v => v.id === id)
            obj.done = !obj.done
        },
        del(id) {
            // splice，会改变原数组，所以不需要重新赋值
            // const index = this.list.findIndex(v => v.id === id)
            // this.list.splice(index, 1)
            // filter,不会改变原数组，所以需要重新赋值
            this.list = this.list.filter(v => v.id !== id)
        },
        add(name) {
            // console.log('name -----> ', name);
            const obj = { id: +new Date(), name, done: false }
            this.list.unshift(obj)
        },
        changeAll(bl) {
            // console.log('bl -----> ', bl);
            this.list.forEach(v => v.done = bl)
        },
        // 清理已完成
        clear() {
            this.list = this.list.filter(v => !v.done)
        }
    }
})